package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.example.config.RocketMQConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author c3886
 */
@Slf4j
@RestController
@RequestMapping("/send")
public class SendController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RocketMQConfigProperties prop;

    @RequestMapping("/common")
    public String common() {
        // 同步发送
        rocketMQTemplate.syncSend(prop.getTopic().get("common"), "syncSend");
        // 异步发送
        rocketMQTemplate.asyncSend(prop.getTopic().get("common"), "asyncSend", new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("Message sent successfully! MessageId: " + sendResult.getMsgId());
            }
            @Override
            public void onException(Throwable e) {
                log.error("Failed to send message: " + e.getMessage(), e);
            }
        });
        // 单程发送
        rocketMQTemplate.sendOneWay(prop.getTopic().get("common"), "sendOneWay");
        return "ok";
    }

    @RequestMapping("/sendx")
    public String simpleSend() {
        rocketMQTemplate.convertAndSend("simple-send-topic", "simple-send-topic simple hello");
        return "ok";
    }
}
